<?php
/**
 * класс предназначен для отслеживания нагрузки
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.1
 */
class Pressure {
	public static $start = null;
	public static $stop = null;

	/**
	 * Устанавливает начальное время выполнения скрипт
	 */
	public static function setStart() {
		list($usec, $sec) = explode(" ", microtime());
		self::$start = (float)$usec + (float)$sec;
	}

	/**
	 * Устанавливает конечное время выполнения скрипт
	 */
	public static function setStop() {
		list($usec, $sec) = explode(" ", microtime());
		self::$stop = (float)$usec + (float)$sec;
	}

	/**
	 * Метод возвращает текущее время выполнения скрипта (разница)
	 *
	 * @return integer
	 */
	public static function calculateCurrentDuration() {
		self::setStop();
		return self::$stop - self::$start;
	}

	/**
	 * Метод сохраняет данные по нагрузке в БД
	 *
	 * @param strung $url
	 * @param integer $type
	 * @param float $duration
	 * @return integer
	 */
	public static function saveDuration($url, $duration) {
		$objDB = Service_Database::instance();
		$stmtFields = "`pressure`.`duration`, `pressure`.`url`, `pressure`.`url_small`, `pressure`.`creation`";
		$stmtValues = "'" . $duration . "', '" . $url . "', '" . Service_Function::getCurrentSmallUrl() . "', '" . Service_Date::gLocalTime2BD() . "'";
		$objSession = User_Session::instance();
	  $userId = $objSession->getUserId();
	  if ($userId) {
	    $stmtFields .= ", `pressure`.`ID_user`";
	  	$stmtValues .= ", '" . $userId . "'";
	  }
		$stmt = "INSERT INTO `pressure`	(" . $stmtFields . ") VALUES (" . $stmtValues . ")";
		return $objDB->query($stmt);
	}

	/**
	 * Получение статистики о нагрузке страниц
	 *
	 * @param $listType - тип нагрузки
	 * @return массив с информацией о нагрузке
	 */
	public static function getPressure($listType) {
		$objDB = Service_Database::instance();
		switch ($listType) {
			case 0:
			  $stmt = "SELECT AVG(`duration`) AS duration, COUNT(`url` ) AS `amount`, `url`
				FROM `pressure`
				WHERE  `creation` > '2008-12-17 00:00:00'
				GROUP BY `url`, `pressure_type`
				ORDER BY 1 DESC
				LIMIT 0, 75";
			  break;
			case 1:
			  $stmt = "SELECT AVG(`duration`) AS duration, COUNT(`url_small` ) AS `amount`, `url_small`
				FROM `pressure`
				WHERE `url_small` != '' AND `creation` > '2008-12-17 00:00:00'
				GROUP BY `url_small`, `pressure_type`
				ORDER BY 1 DESC
				LIMIT 0, 75";
			  break;
			case 2:
			  $stmt = "SELECT SUM(`duration`) AS duration, COUNT(`url_small` ) AS `amount`, `url_small`
				FROM `pressure`
				WHERE `url_small` != '' AND `creation` > '2008-12-17 00:00:00'
				GROUP BY `url_small`, `pressure_type`
				ORDER BY 1 DESC
				LIMIT 0, 75";
			  break;
			default:
			  $stmt = "SELECT AVG(`duration`) AS duration, COUNT(`url` ) AS `amount`, `url`
				FROM `pressure`
				WHERE  `creation` > '2008-12-17 00:00:00'
				GROUP BY `url`, `pressure_type`
				ORDER BY 1 DESC
				LIMIT 0, 75";
			  break;
		}
		return $objDB->select($stmt);
	}
}
?>